<template>
  <div class="loading2v2">
    <div class="loading-text">2v2 Loading...</div>
    <div class="progress-container">
      <div class="progress-bar" :style="{ width: progress + '%' }"></div>
    </div>
    <div class="progress-text">{{ Math.round(progress) }}%</div>
  </div>
</template>

<script setup>
import { onMounted, onBeforeUnmount, ref } from 'vue'
import { useRouter } from 'vue-router'
import ws from '@/services/websocket'
import { useRoomStore } from '@/stores/room'
import Poker from '@/models2v2/poker'

const roomStore = useRoomStore()
const router = useRouter()

// 进度条相关状态
const progress = ref(0)
const dataLoaded = ref(false)
let progressTimer = null
let checkTimer = null
let retryTimer = null

// 检查数据是否加载完成
function checkDataLoaded() {
  const room2v2 = roomStore.getRoom2V2()
  const hasPlayers = room2v2.players && room2v2.players.length === 4 && 
                     room2v2.players.every(p => p.uid && p.nickname)
  const hasPile = room2v2.pile && room2v2.pile.length > 0
  const hasCharacArray = roomStore.characArray && roomStore.characArray.length === 4
  
  return hasPlayers && hasPile && hasCharacArray
}

// 开始进度条动画
function startProgress() {
  // 3秒内从0%到85%
  const duration = 3000
  const targetProgress = 85
  const startTime = Date.now()
  
  progressTimer = setInterval(() => {
    const elapsed = Date.now() - startTime
    const currentProgress = Math.min((elapsed / duration) * targetProgress, targetProgress)
    progress.value = currentProgress
    
    if (currentProgress >= targetProgress) {
      clearInterval(progressTimer)
      progressTimer = null
      // 到达85%后开始检查数据
      startDataCheck()
    }
  }, 16) // 约60fps
}

// 开始数据检查
function startDataCheck() {
  let checkCount = 0
  const maxChecks = 50 // 5秒 = 50 * 100ms
  
  checkTimer = setInterval(() => {
    checkCount++
    //检查数据成功
    if (checkDataLoaded()) {
      // 数据加载完成，1秒后到100%
      clearInterval(checkTimer)
      checkTimer = null
      dataLoaded.value = true
      
      setTimeout(() => {
        const duration = 1000
        const startProgress = 85
        const targetProgress = 100
        const startTime = Date.now()
        
        const finishTimer = setInterval(() => {
          const elapsed = Date.now() - startTime
          const currentProgress = startProgress + (elapsed / duration) * (targetProgress - startProgress)
          progress.value = Math.min(currentProgress, targetProgress)
          
          if (currentProgress >= targetProgress) {
            clearInterval(finishTimer)
            // 进度条完成，跳转到season页面
            console.log('加载完成！跳转到season页面')
            router.push({
              path: '/season',
              query: {
                type: '2v2custom'
              }
            })
          }
        }, 16)
      }, 1000)
    } else if (checkCount >= maxChecks) {
      // 5秒后数据仍未加载完成，重新获取数据
      clearInterval(checkTimer)
      checkTimer = null
      retryGetAll()
    }
  }, 100) // 每100ms检查一次
}

// 重新获取数据
function retryGetAll() {
  console.log('数据未加载完成，重新获取数据...')
  getall()
  startDataCheck() // 重新开始检查
}

// 获取所有数据
function getall() {
  try {
    const payload = {
      genre: 4,
      type: 'getall',
      rid: roomStore.room_id
    }
    ws.send(JSON.stringify(payload))
    console.log('发送获取所有数据请求:', payload)
  } catch (e) {
    console.error('发送获取所有数据请求失败:', e)
  }
}

// 处理服务器返回的所有数据
function handleBackAll(message) {
  // 处理 players 字段
  //players字段存在并且是数组类型的
  if (message?.players && Array.isArray(message.players)) {
    const room2v2 = roomStore.getRoom2V2()
    message.players.forEach((playerData, index) => {
      if (index < 4 && room2v2.players[index]) {
        room2v2.players[index].uid = playerData.uid || ''
        room2v2.players[index].nickname = playerData.nickname || ''
        room2v2.players[index].position = playerData.position || 0
        room2v2.players[index].profile = playerData.profile || ''
      }
    })
  }
  // 处理 shuffledQueue 字段
  if (message?.shuffledQueue && Array.isArray(message.shuffledQueue)) {
    const room2v2 = roomStore.getRoom2V2()
    
    // 清空现有牌堆
    room2v2.pile = []
    
    // 遍历 shuffledQueue 创建 Poker 对象
    message.shuffledQueue.forEach((cardData, index) => {
      try {
        const poker = new Poker(
          cardData.id || 0,
          cardData.count || 0,
          cardData.color || 0,
          cardData.name || '',
          cardData.type || ''
        )
        room2v2.pile.push(poker)
      } catch (error) {
        console.error(`创建第 ${index} 张牌失败:`, cardData, error)
      }
    })
  }
  //处理message.assignment字段
  console.log("原始 assignment 数据:", message.assignment);
  
  if (message.assignment && typeof message.assignment === 'object') {
    // 提取 P1, P2, P3, P4 的数组并合并
    const p1Array = message.assignment.P1 || [];
    const p2Array = message.assignment.P2 || [];
    const p3Array = message.assignment.P3 || [];
    const p4Array = message.assignment.P4 || [];
    
    // 创建二维数组，每个玩家的数组作为子数组
    const characArray2D = [p1Array, p2Array, p3Array, p4Array];
    
    // 存储到 characArray
    roomStore.setCharacArray(characArray2D);
  }
  
  const room2v2 = roomStore.getRoom2V2()
  console.log("room2v2:")
  console.log(room2v2);
  console.log("最终 roomStore.characArray:")
  console.log(roomStore.characArray);
  
  // 设置玩家阵营
  setPlayerCamps()
}

// 设置玩家阵营的函数
function setPlayerCamps() {
  const mypos = roomStore.mypos
  const room2v2 = roomStore.getRoom2V2()
  
  console.log('设置阵营，mypos:', mypos)
  
  if (mypos === 1 || mypos === 4) {
    // mypos = 1 或 4，设置阵营1
    if (room2v2.players[0]) room2v2.players[0].camp = 1
    if (room2v2.players[3]) room2v2.players[3].camp = 1
    // 设置阵营2
    if (room2v2.players[1]) room2v2.players[1].camp = 2
    if (room2v2.players[2]) room2v2.players[2].camp = 2
  } else if (mypos === 2 || mypos === 3) {
    // mypos = 2 或 3，设置阵营2
    if (room2v2.players[0]) room2v2.players[0].camp = 2
    if (room2v2.players[3]) room2v2.players[3].camp = 2
    // 设置阵营1
    if (room2v2.players[1]) room2v2.players[1].camp = 1
    if (room2v2.players[2]) room2v2.players[2].camp = 1
  }
  
  console.log('阵营设置完成:')
  room2v2.players.forEach((player, index) => {
    console.log(`玩家${index}: camp = ${player.camp}`)
  })
}

onMounted(() => {
  ws.on(4, 'backall', handleBackAll)
  getall() // 组件挂载时自动获取数据
  startProgress() // 开始进度条动画
})

onBeforeUnmount(() => {
  ws.off(4, 'backall')
  // 清理所有定时器
  if (progressTimer) clearInterval(progressTimer)
  if (checkTimer) clearInterval(checkTimer)
  if (retryTimer) clearTimeout(retryTimer)
})
</script>

<style scoped>
.loading2v2 {
  width: 100%;
  height: 120px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-size: 20px;
  background: rgba(0, 0, 0, 0.3);
  padding: 20px;
}

.loading-text {
  margin-bottom: 15px;
  font-size: 18px;
  color: #fff;
}

.progress-container {
  width: 300px;
  height: 8px;
  background-color: #333;
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 10px;
  border: 1px solid #555;
}

.progress-bar {
  height: 100%;
  background: linear-gradient(90deg, #fff 0%, #ccc 100%);
  border-radius: 4px;
  transition: width 0.1s ease;
  box-shadow: 0 0 5px rgba(255, 255, 255, 0.3);
}

.progress-text {
  font-size: 14px;
  color: #fff;
  font-weight: bold;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5);
}
</style>


